// @ts-nocheck

//获取设备
export function initDevice(): { device: string; browser: "wx" | "" } {
    const ua = navigator.userAgent.toLowerCase();
    let device;
    let browser = "";
    // 浏览器
    if (/android|adr/gi.test(ua)) {
        // 安卓
        device = "android";
    } else if (/\(i[^;]+;( U;)? CPU.+Mac OS X/gi.test(ua)) {
        //苹果
        device = "ios";
    } else if (/iPad/gi.test(ua)) {
        //ipad
        device = "ipad";
    }
    if (ua.match(/MicroMessenger/i) == "micromessenger") {
        browser = "wx";
    }
    return { device, browser };
}

//app交互
export function $webViewOnMethod(type: appEnum, data?: any) {
    const { device } = initDevice(); //得到设备机型
    if (device === "ios") {
        const obj = { type, data };
        if (!window.webkit) return false;
        window.webkit.messageHandlers.onWebMethod.postMessage(obj);
    } else if (device === "android") {
        if (data) {
            if (Object.prototype.toString.call(data) === "[object Object]")
                data = JSON.stringify(data);
            else data = data.toString();
        }
        if (!window.Android) return false;
        window.Android.onWebMethod(type, data);
    } else console.error("安卓和ios判断都没进去");
}

//app转发服务端消息(调用h5方法)
window.apptransitMessage = function (data: any) {
    if (typeof data === "string") {
        try {
            data = JSON.parse(data);
        } catch (error) {
            console.log(error);
        }
    }
    try {
        const { noticeCode } = data;
        (window.apptransitMessage.handlerMap[noticeCode] || []).forEach((fun) => {
            try {
                fun(data);
            } catch (e) {
                console.log(e);
            }
        });
    } catch (error) {
        console.log(error);
    }
};
window.apptransitMessage.handlerMap = {};
window.apptransitMessage.register = function (code: number, handler: Function) {
    window.apptransitMessage.handlerMap[code] ||
        (window.apptransitMessage.handlerMap[code] = []);
    window.apptransitMessage.handlerMap[code].indexOf(handler) !== -1 ||
        window.apptransitMessage.handlerMap[code].push(handler);
};

//和app交互枚举
//bettermoyan.app://
export enum appEnum {
    BACK = "BACK", //返回键
    TO_PAGE = "TO_PAGE", //跳转到某个页面
    CLOSE = "CLOSE", //关闭网页
    LINKSHARE = "LINKSHARE", //链接分享
    IMGSHARE = "IMGSHARE", //海报分享
    NO_MONEY = "NO_MONEY", //抽奖金币不足
    NO_MONEY_TO_PAGE = "NO_MONEY_TO_PAGE", //余额不足跳转邀请/任务
    WINDOW_NOTICE = "WINDOW_NOTICE", //app调用我们的方法
    NATIVE_PAY = "NATIVE_PAY", //H5调用原生支付
    TO_SERVICE = "TO_SERVICE", //跳转客服
    TO_EXTERNAL_PAGE = "TO_EXTERNAL_PAGE", //跳转外部网页
    ANDROID_REAL_NAME = "ANDROID_REAL_NAME", //安卓实名认证
}

